<template>
  <div class="quill-editor-container">
    <!-- 隐藏的文件上传组件 -->
    <el-upload
        class="editor-upload"
        action="#"
        :show-file-list="false"
        :before-upload="beforeImageUpload"
        :http-request="handleImageUpload"
    >
    </el-upload>

    <QuillEditor
        ref="editor"
        v-model:content="content"
        :options="editorOptions"
        contentType="html"
        theme="snow"
        @update:content="handleContentChange"
    />
  </div>
</template>

<script setup>
import {computed, ref, watch} from 'vue'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import {useTokenStore} from "@/stores/tokenStore.js";

const SERVER_ADDR = import.meta.env.VITE_SERVER_ADDR // 从环境变量获取

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['update:modelValue'])

const content = ref(props.modelValue)
const editor = ref(null)
// 携带token进行文件上传
const tokenStore = useTokenStore();
const token = tokenStore.tokenStr;
// const headers = computed(() => {
//   const token = tokenStore.tokenStr;
//   return{
//     token: token
//   }
// })
// 编辑器配置
const editorOptions = {
  modules: {
    toolbar: {
      container: [
        ['bold', 'italic', 'underline', 'strike'],
        ['blockquote', 'code-block'],
        [{ 'header': 1 }, { 'header': 2 }],
        [{ 'list': 'ordered' }, { 'list': 'bullet' }],
        [{ 'script': 'sub' }, { 'script': 'super' }],
        [{ 'indent': '-1' }, { 'indent': '+1' }],
        [{ 'direction': 'rtl' }],
        [{ 'size': ['small', false, 'large', 'huge'] }],
        [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
        [{ 'color': [] }, { 'background': [] }],
        [{ 'font': [] }],
        [{ 'align': [] }],
        ['link', 'image', 'video'],
        ['clean']
      ],
      handlers: {
        image: () => {
          // 触发隐藏的文件上传
          document.querySelector('.editor-upload input').click()
        }
      }
    }
  },
  placeholder: '请输入内容...'
}

// 处理图片上传前校验
const beforeImageUpload = (file) => {
  const isImage = ['image/jpeg', 'image/png', 'image/gif'].includes(file.type)
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传 JPG/PNG/GIF 格式的图片!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过5MB!')
    return false
  }
  return true
}

// 自定义图片上传
const handleImageUpload = async (options) => {
  const { file } = options
  const formData = new FormData()
  formData.append('pic', file)

  try {
    const { data } = await axios.post(
        `${SERVER_ADDR}/scenicSpot/upload`,
        formData,
        {
          headers: {
            'Content-Type': 'multipart/form-data',
            'Token': token,
          }
        }
    )

    if (data.code === 10000) {
      insertToEditor(`${SERVER_ADDR}/scenicSpot/pic/${data.data}`)
    } else {
      ElMessage.error(data.message || '上传失败')
    }
  } catch (error) {
    ElMessage.error('上传失败，请重试')
    console.error('上传错误:', error)
  }
}

// 将图片插入编辑器
const insertToEditor = (url) => {
  const quill = editor.value.getQuill()
  const range = quill.getSelection()?.index || 0

  quill.insertEmbed(range, 'image', url)
  quill.setSelection(range + 1)
}

// 内容变化处理
const handleContentChange = (value) => {
  emit('update:modelValue', value)
}

// 监听prop变化
watch(() => props.modelValue, (newVal) => {
  if (newVal !== content.value) {
    content.value = newVal
  }
})
</script>

<style scoped>
.quill-editor-container {
  background: white;
}

:deep(.ql-editor) {
  min-height: 300px;
}

.editor-upload {
  display: none;
}
</style>